package com.zynn.service.module.calculate.Java;

import java.util.concurrent.TimeUnit;

/**
 * @author yilabao
 *
 * volatile 关键字
 *
 * 线程如果修改 volatile 通知其它线程该变量已经被修改
 *
 */
public class VolatileDemo {

    public static void main(String[] args) {
        MyData data = new MyData();
        new Thread(()->{
            System.out.println("come in == "+Thread.currentThread().getName());

            try {
                TimeUnit.SECONDS.sleep(3);
                data.addTo60();

            } catch (InterruptedException e){
                System.out.println(e.getMessage());
            }
            System.out.println("值修改完毕");

            // 开始执行增加数值操作
        },"thread_1").start();


        // while number == 0 则main线程一直运行
        while ( data.number == 0) {
            System.out.println("进来修改");
        }
        System.out.println("通知 成功");
    }
}

/**
 * 定义volatile定义 属性值可见性
 *
 * 发生改变通知其它线程
 */
class MyData {

    volatile int number = 0;

    void addTo60() {
        this.number = 60;
    }
}
